package com.open.party.cloud.view.home.dangYuanJiaoYu

import android.os.Bundle
import android.util.Log
import cn.android.x.model.data.ResultInfo
import com.gyf.immersionbar.ImmersionBar
import com.open.party.cloud.R
import com.open.party.cloud.model.StudyRecordBean
import com.open.party.cloud.model.StudyRecordVo
import com.open.party.cloud.model.YunKePlayBean
import com.open.party.cloud.view.base.VideoEntity
import com.open.party.cloud.view.base.VideoPlayerBaseActivity
import com.open.party.cloud.view.home.dangYuanJiaoYu.adapter.LiangDuYunKeTangPlayListAdapter
import com.open.party.cloud.viewModel.StudyViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.rxretrofit.bean.PageVo
import kotlinx.android.synthetic.main.video_play_activity.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 课程视频播放详情页面
 */
class YunKeTangStudyVideoActivity : VideoPlayerBaseActivity<YunKePlayBean>() {

    private var isStart = false
    private var isFinish = false
    private var cmId = ""
    private var learnId = ""

    var viewModel: StudyViewModel? = null

    override fun getLayoutResId(): Int = R.layout.video_play_activity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setViewTitle("视频课程学习")
        viewModel = StudyViewModel()
        initData()
    }

    private fun initData() {
        isStart = intent.getBooleanExtra("isStart", false)
        isFinish = intent.getBooleanExtra("isFinish", false)
        cmId = intent.getStringExtra("cmId") as String
        learnId = intent.getStringExtra("learnId") as String

        // 处理播放数据
        val videoSource = intent.getSerializableExtra("DataSource") as VideoEntity
        playingDataSource = getDataSourceByVideoSource(videoSource)

        // 下面列表
        initRecycleView(videoSource.sid)
    }

    // 下面列表
    private var adapter: LiangDuYunKeTangPlayListAdapter? = null
    private var yunKePlayList: ArrayList<YunKePlayBean>? = null

    private fun initRecycleView(playingId: String) {
        yunKePlayList = ArrayList()
        for (yunKePlayBean in YunKeTangClassListActivity.yunKePlayList!!) {
            if (yunKePlayBean.type != null
                && XUtils.string().isNotEmpty(yunKePlayBean.type.code)
                && yunKePlayBean.type.code == "SP"
            ) {
                yunKePlayBean.isPlaying = playingId == yunKePlayBean.id
                yunKePlayList!!.add(yunKePlayBean)
            }
        }

        // 显示
        initRecycleLinearView(loadingRecyclerView)

        adapter = LiangDuYunKeTangPlayListAdapter(this)
        loadingRecyclerView.adapter = adapter

        adapter!!.setData(yunKePlayList)

        loadingRecyclerView.setPullRefreshEnabled(false)
        loadingRecyclerView.setLoadingMoreEnabled(false)

        adapter!!.setOnSuperListener { position, yunKePlayBean, _ ->

            if (yunKePlayBean.type == null && XUtils.string().isEmpty(yunKePlayBean.type.code)) {
                return@setOnSuperListener
            }

            if (yunKePlayBean.type.code == "SP") {

                if (playingDataSource.sid == yunKePlayBean.id) {
                    return@setOnSuperListener
                }

                // 构造播放数据
                val videoSourceEntity = VideoEntity()
                videoSourceEntity.title = yunKePlayBean.name
                videoSourceEntity.url = yunKePlayBean.fileUrl
                videoSourceEntity.sid = yunKePlayBean.id
                playingDataSource = getDataSourceByVideoSource(videoSourceEntity)

                startPlay()

                // 刷新播放状态
                for (index in yunKePlayList!!.indices) {
                    yunKePlayList!![index].isPlaying = false
                }
                yunKePlayList!![position].isPlaying = true

                adapter!!.notifyDataSetChanged()
            } else {

            }
        }
    }

    override fun loadData(pageVo: PageVo<YunKePlayBean>?) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<StudyRecordBean>) {
        if ("saveOrUpdateStudyRecord" != result.eventType) {
            return
        }

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    if ("isStart" == result.msg) {
                        isStart = true
                    }
                    if ("isFinish" == result.msg) {
                        isFinish = true
                    }
                    XUtils.toast().show("记录成功")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
                XUtils.toast().show("Token过期，请重新登录")
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    private fun getRecordBean(isFinish: Boolean, times: Long): StudyRecordVo {
        val vo = StudyRecordVo()
        vo.state = isFinish
        vo.learnId = XUtils.string().getNotNullValue(learnId)
        vo.cmId = XUtils.string().getNotNullValue(cmId)
        vo.learningDuration = times
        return vo
    }

    override fun onPlayStart() {
        if (!isStart && !isFinish) {
            val vo: StudyRecordVo = getRecordBean(false, 0)
            viewModel!!.saveOrUpdateStudyRecord(vo, "isStart")
//            Log.d("initLis", "onPlayStart 要传");
        } else {
//            Log.d("initLis", "onPlayStart 不传");
        }
    }

    override fun onPlayEnd(currentPosition: Int) {
        if (!isFinish) {
            val vo = getRecordBean(true, (currentPosition / 1000).toLong())
            viewModel!!.saveOrUpdateStudyRecord(vo, "isFinish")

//            Log.e("initLis", "onPlayEnd 传");

        } else {
//            Log.e("initLis", "onPlayEnd 不传");
        }
    }


    var lastUploadTime = 0

    override fun onPlaying(currentPosition: Int) {

        val times = currentPosition / (1 * 60 * 1000) // 一分钟

        if (lastUploadTime != times) {
            if (isStart && !isFinish) {
                lastUploadTime = times

                val dataTime = currentPosition / 1000

                val vo = getRecordBean(false, dataTime.toLong())
                viewModel!!.saveOrUpdateStudyRecord(vo, "")

                Log.e("saveOrUpdateStudyRecord", "onPlaying = currentPosition: $currentPosition up: $dataTime");
            } else {
//                Log.e("initLis", "onPlaying 不传 isStart&&!isFinish不够");
            }
        } else {
//            Log.e("initLis", "onPlaying 不传 时间不够");
        }
    }
}